//
//  ImageAnimationViewController.m
//  ImageAnimation
//
//  Created by apple on 8/16/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ImageAnimationViewController.h"
#import "DraggableView.h"
#import "FixFrame.h"
#import "StartViewController.h"
@implementation ImageAnimationViewController
@synthesize columnsCount;
@synthesize rowsCount;
@synthesize clearFixFrame;
@synthesize startViewController;
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    position = 0;
    CGRect wholeScreen = [[UIScreen mainScreen]bounds];
    UIImage *image1 = [UIImage imageNamed:@"4.jpg"];
    UIImage *image2 = [UIImage imageNamed:@"2.jpg"];
//    
//    CGRect rect1 = CGRectMake(0 , 0, wholeScreen.size.width/2, wholeScreen.size.height/2);
//    
//    UIImage *a1 = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([image1 CGImage], CGRectMake(0, 0, 200, 200))];
//    UIImage *a2 = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([image1 CGImage], CGRectMake(200, 0, 200, 200))];

    NSMutableArray *imageArray = [NSMutableArray arrayWithObjects:image1,image2, nil];
    
    if (CGRectGetHeight(wholeScreen) > CGRectGetWidth(wholeScreen)) {
        int height = wholeScreen.size.width;
        wholeScreen.size.width = wholeScreen.size.height;
        wholeScreen.size.height = height;
    }
    UIImageView *fishAni = [[UIImageView alloc]initWithFrame:wholeScreen];
    fishAni.animationImages = imageArray;
    fishAni.animationRepeatCount = 10;
    fishAni.animationDuration =1;
    
    [fishAni startAnimating];
    fixFrameArray = [[NSMutableArray alloc] init];
    array = [self devideImage:image2];
    randomArray = [[NSMutableArray alloc] initWithArray:array];
    [randomArray removeLastObject];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timerAnimation) userInfo:nil repeats:YES];

    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}
- (void)timerAnimation{
    [self runAnimation];
}

- (void)runAnimation{
    
    int count = [randomArray count];
    if (position < rowsCount*columnsCount ) {
        
        CGRect frame = [self getFrameFromPosition:position];
        DraggableView *imageView = nil;
        if (position == rowsCount*columnsCount - 1) {
            imageView = [array lastObject];
        }else{
            imageView = [randomArray objectAtIndex:rand()%count]; 
        }
        [imageView setHorizontalIndex:position%columnsCount];
        [imageView setVerticalIndex:position/rowsCount];
        [imageView setFrame:frame];
        [self.view addSubview:imageView];
        [randomArray removeObject:imageView];  
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:1];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [imageView setAlpha:1];
        //[imageView setFrame:CGRectMake(position*200, 0, 200, 200)];
        [UIView commitAnimations];
    }else{
        [timer invalidate];
    }
    position++;
}
- (NSMutableArray *)devideImage:(UIImage *)image{
    
    NSMutableArray *images = [NSMutableArray array];
    CGRect wholeScreen = [[UIScreen mainScreen]bounds];
    wholeScreen.size.width = 1024;
    wholeScreen.size.height = 748;
    
    float columnNumber = 2;
    float rowNumber = 2;
    rowsCount = rowNumber;
    columnsCount = columnNumber;
    clearFixFrame = [[FixFrame alloc] initWithHorizontal:columnsCount andVertical:rowsCount-1];
    
    for (int v = 0 ; v < rowNumber; v++) {
        NSMutableArray *horizontalArray = [NSMutableArray arrayWithCapacity:columnNumber];
        [fixFrameArray addObject:horizontalArray];
    }
    float interval = 0;// pix
    float width = (CGRectGetWidth(wholeScreen) - (columnNumber + 1)*interval)/(columnNumber + 1);
    
    float height = (CGRectGetHeight(wholeScreen) - (rowNumber + 1)*interval)/(rowNumber);
    CGRect defaultFixFrame = CGRectMake(columnsCount*(width + interval) + interval, (rowsCount- 1)*(height + interval) + interval, width, height);
    [clearFixFrame setFixFrameValue:defaultFixFrame];
    CGRect menuFrame = CGRectMake(columnsCount*(width + interval) + interval, 0, width, (rowsCount- 1)*(height + interval) + interval);
    menuView = [[UIView alloc] initWithFrame:menuFrame];
    [menuView setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:menuView];
    UIButton *back = [[UIButton alloc] initWithFrame:menuView.bounds];
    [back setTitle:@"Back" forState:UIControlStateNormal];
    [back.titleLabel setFont:[UIFont systemFontOfSize:40]];
    [back addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchDragInside];
    [menuView addSubview:back];
    //image
    for (float i=0;i<rowNumber;i++) {
        for (float j=0;j<columnNumber;j++) {
            CGRect subFrame = CGRectMake(j*(width + interval) + interval, i*(height + interval) + interval, width, height);
            UIImage *partImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([image CGImage], subFrame)];
            DraggableView *imageView = [[DraggableView alloc] initWithFrame:subFrame];
            [imageView setTargetHorizontalIndex:j];
            [imageView setTargetVerticalIndex:i];
            [imageView setController:self];
            [imageView setImage:partImage];
            imageView.userInteractionEnabled = YES;
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
            [imageView setAlpha:0];
            [images addObject:imageView];
            
            
            FixFrame *fixFrame = [[FixFrame alloc] initWithHorizontal:j andVertical:i];
            [fixFrame setFixFrameValue:subFrame];
            [fixFrame setDraggableView:imageView];
            
            NSMutableArray *horizontalArray = [fixFrameArray objectAtIndex:i];
            [horizontalArray insertObject:fixFrame atIndex:j];
        }
    }
    return images;
}



- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
        return YES;
    }
    return NO;
}


- (void)moveLeft:(DraggableView *)draggableView{
    
    
    
}
- (void)moveUp:(DraggableView *)draggableView{
    
}
- (void)moveRight:(DraggableView *)draggableView{
    
}
- (void)moveDown:(DraggableView *)draggableView{
    
}

- (FixFrame *)findFixFrameHorizontal:(NSInteger)h andVertical:(NSInteger)v{
//    NSLog(@"clear (h,v) = (%d,%d)",self.clearFixFrame.horizontalIndex,self.clearFixFrame.verticalIndex);
    if (h == self.clearFixFrame.horizontalIndex && v == self.clearFixFrame.verticalIndex) {
        return self.clearFixFrame;
    } 
    return nil;
}

- (CGRect)getFrameFromHorizontal:(NSInteger)h andVertical:(NSInteger)v{
    NSArray *horizontalArray = [fixFrameArray objectAtIndex:v];
    if (horizontalArray) {
        FixFrame *target = [horizontalArray objectAtIndex:h];
        return target.fixFrameValue;
    }   
    return CGRectMake(0, 0, 0, 0);
}

- (CGRect)getFrameFromPosition:(NSInteger)p{
    int v = p/rowsCount;
    int h = p%columnsCount;
    return [self getFrameFromHorizontal:h andVertical:v];
}

- (void)moveAnimaiton:(DraggableView *)draggableView withFrame:(CGRect)frame{
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.2];
    [draggableView setFrame:frame];
    [UIView commitAnimations];
}


-(UIImage*)resizedImage:(UIImage*)inImage  inRect:(CGRect)thumbRect {

    UIGraphicsBeginImageContext(thumbRect.size);
    [inImage drawInRect:thumbRect];
    return UIGraphicsGetImageFromCurrentImageContext();
    
    
    
}

- (void)clickBack{
    [self.startViewController dismissModalViewControllerAnimated:YES]; 
}


@end
